package cc.linker.steplink.crm.merchant.service;

import cc.linker.steplink.crm.commons.utils.NumberUtils;
import cc.linker.steplink.crm.merchant.dao.ContentMapper;
import cc.linker.steplink.crm.merchant.dao.ShopGoodsColumnDao;
import cc.linker.steplink.crm.merchant.dao.ShopGoodsMapper;
import cc.linker.steplink.crm.merchant.pojo.ContentPo;
import cc.linker.steplink.crm.merchant.pojo.ShopGoods;
import cc.linker.steplink.crm.merchant.service.integral.IntegralGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ShopGoodsColumnService {
    @Autowired
    private ShopGoodsColumnDao shopGoodsColumnDao;
    @Autowired
    private NewMallService newMallService;
    @Autowired
    private ShopGoodsService shopGoodsService;
    @Autowired
    private ShopGoodsMapper shopGoodsMapper;
    @Autowired
    private ContentMapper contentMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IntegralGoodsService integralGoodsService;

    //添加专栏
    public boolean save(Map<String, Object> params) {
        String columnId = null;
        if (params.get("columnId") != null) {
            columnId = params.get("columnId").toString();
        }
        String introduce = (String) params.get("introduce");
        String cover = (String) params.get("cover");
        List group = (List) params.get("group");
        String title = (String) params.get("title");
        Integer status = Integer.valueOf(params.get("status").toString());
        Double price = Double.valueOf(params.get("price").toString());
        Double originalCost = (double) 0;
        if(null != params.get("originalCost")){
            originalCost = Double.valueOf(params.get("originalCost").toString());
        }
        params.put("columnId", columnId);
        params.put("goodsContent", introduce);
        params.put("goodsCover", cover);
        params.put("goodsGroup", group);
        //params.put("goodsId",entity.getGoodsId());
        params.put("goodsName", title);
        params.put("goodsStatus", status);
        params.put("purchaseType", 2);
        params.put("goodsType", 4);
        params.put("moneyAmount", price);
        params.put("originalCost", originalCost);
        //先存商品
        newMallService.savePublic(params);
        if (columnId != null) {
            Map<String, Object> shopGoodsColumnDetail = shopGoodsColumnDao.getShopGoodsColumnDetail(params);
            LOGGER.info("shopGoodsColumnDetail===[{}]", shopGoodsColumnDetail);
            Integer isFree = (Integer) shopGoodsColumnDetail.get("isFree");
            String goodsId = shopGoodsColumnDetail.get("goodsId").toString();
            if (params.get("isFree") != null) {
                String newIsFree = params.get("isFree").toString();
                if (isFree == 0 && "1".equals(newIsFree)) {
                    // 当专栏从收费转为免费，若此专栏参与返润，则将此商品转为“不参与”
                    this.notJoining(goodsId);
                    List<String> contentGoodsIdList = shopGoodsColumnDao.getContentGoodsIdListByColumnId(columnId);
                    // 专栏下的内容也一样
                    for (String contentGoodsId : contentGoodsIdList) {
                        this.notJoining(contentGoodsId);
                    }
                }
            }
            Boolean flag = shopGoodsColumnDao.update(params);
            if(flag){
                if(!StringUtils.isEmpty(shopGoodsColumnDetail.get("goodsId"))){
                    //判断积分商品是否失效
                    integralGoodsService.updateGoodsToIntegralGoods(Long.valueOf(shopGoodsColumnDetail.get("goodsId").toString()), params, null,null);
                }
            }
            return flag;
        } else {
            return shopGoodsColumnDao.insert(params);
        }
    }

    /**
     * 把商品转为不参与推广,并从大b商城移除
     *
     * @param goodsId 商品id
     */
    public void notJoining(String goodsId) {
        Map<String, Object> map = new HashMap<>();
        map.put("promotion", "0");
        map.put("rebate", "0");
        map.put("goodsId", goodsId);
        map.put("orgMall", "0");
        shopGoodsMapper.promotion(map);
        shopGoodsMapper.deleteAssociationForMyShopByGoodsId(map);
    }

    //获取专栏列表
    public List<Map<String, Object>> getShopGoodsColumnList(Map<String, Object> params) {
        List<Map<String, Object>> listMap = shopGoodsColumnDao.getShopGoodsColumnList(params);
        for (Object item : listMap) {
            Map<String, Object> map = (Map<String, Object>) item;

            long moneyAmount = map.get("moneyAmount") != null ? Long.parseLong(map.get("moneyAmount").toString()) : 0;
//            DecimalFormat df = new DecimalFormat("#.00");
//            double m = ((double) moneyAmount / 100);
            map.put("moneyAmountConvert", NumberUtils.fenToYuan(moneyAmount));//金额分转元

            long originalPrice = map.get("originalPrice") != null ? Long.parseLong(map.get("originalPrice").toString()) : 0;
//            double p = ((double) originalPrice / 100);
            map.put("originalPriceConvert", NumberUtils.fenToYuan(originalPrice));//原价分转院
        }
        return listMap;
    }

    //获取专栏总条数
    public Integer getShopGoodsColumnListCount(Map<String, Object> params) {
        return shopGoodsColumnDao.getShopGoodsColumnListCount(params);
    }

    /*
     * 更新专栏
     * Status：更新值
     * Type：更新类型 0：更新状态(COLUMN_STATUS 1.更新中 2.已完结) 1：删除 2：更新商品状态(GOODS_STATUS 0 待上架 1 上架中 2 已下架)
     * */
    public boolean updateColumnStatus(Long columnId, Integer status, Integer type, String adminId, String orgId, Boolean ifSales) {
        Map<String, Object> mapColumn = shopGoodsColumnDao.getShopGoodsColumnModel(columnId);
        Long goodsId = (Long) mapColumn.get("GOODS_ID");

        redisTemplate.delete("goodsInfo:goods_info_" + goodsId);

        Integer mine = 0;
        ShopGoods shopGoods = shopGoodsService.getGoods(goodsId);
        String belongId = shopGoods.getBelongId();
        if (belongId != null && !belongId.equals("") && !ifSales) {
            mine = 1;
        }
        if (type == 1) {
            Long[] goodsIds = new Long[]{goodsId};
            shopGoodsService.delete(goodsIds, adminId, orgId, mine, ifSales);// 删除商品
            //shopGoodsMapper.delete(goodsIds);   // 删除商品
            if (mine == 0) {
                List<Long> contentIds = contentMapper.getColumnContentList(columnId);
                if (contentIds != null && contentIds.size() > 0) {
                    for (Long contentId : contentIds) {
                        Map map = new HashMap();
                        map.put("columnId", columnId);
                        map.put("contentId", contentId);
                        DeleteCloumnContent(map);
                    }
                }
                return shopGoodsColumnDao.updateColumnStatus(columnId, status, type);
            }
            //删除商品 积分商品异常
            shopGoodsMapper.updateIntegralGoods(goodsIds);
            return true;
        } else if (type == 2) {
            Map maps = new HashMap();
            maps.put("goodsId", goodsId);
            maps.put("orgId", orgId);
            if (!ifSales) {
                newMallService.changeGoodStatus(maps, mine);
            } else {
                maps.put("mine", mine);
                maps.put("adminId", adminId);
                newMallService.updateStatus(maps);
            }
            return true;
            //return shopGoodsMapper.updateStatus(map);  //更新商品状态(GOODS_STATUS 0 待上架 1 上架中 2 已下架)
        } else {
            return shopGoodsColumnDao.updateColumnStatus(columnId, status, type);
        }

    }

    /*
     * 获取专栏、商品关联信息
     * */
    public Map<String, Object> getShopGoodsColumnDetail(long columnId, String belongId) {
        Map<String, Object> maps = new HashMap<>();
        maps.put("columnId", columnId);
        maps.put("belongId", belongId);
        Map<String, Object> map = shopGoodsColumnDao.getShopGoodsColumnDetail(maps);
        // 获取关联的标签
        Long goodsId = shopGoodsMapper.getGoodsIdByColumnId(columnId);
        List<Map<String, Object>> labels = shopGoodsMapper.getGoodsLabelsById(goodsId);
        map.put("labels",labels);

        Object columnGroup = map.get("columnGroup");
        if (columnGroup != null) {
            map.put("columnGroup", columnGroup.toString());
        }
        long moneyAmount = map.get("moneyAmount") != null ? Long.parseLong(map.get("moneyAmount").toString()) : 0;
        DecimalFormat df = new DecimalFormat("#.00");
        //分转元
        double s = ((double) moneyAmount / 100);
        map.put("moneyAmountConvert", Double.valueOf(df.format(s)));
        map.put("originalCost", Double.valueOf(NumberUtils.fenToYuan(Long.valueOf(map.get("originalCost").toString()))));
        return map;
    }

    /*
     * 添加专栏、内关联
     * columnId：专栏ID
     * contentIds：内容ID
     * */
    public boolean AddCloumnContent(Map<String, Object> params) {
        Long columnId = params.get("columnId") != null ? Long.parseLong(params.get("columnId").toString()) : 0;
        List contentIds = (List) params.get("contentIds");
        Map<String, Object> map = shopGoodsColumnDao.getShopGoodsColumnModel(columnId);
        Integer COLUMN_STATUS = (Integer) map.get("COLUMN_STATUS");
        if (COLUMN_STATUS == 2) {
            params.put("msg", "此专栏已完结，无法添加");
            return false;
        }
        Integer maxSerialNum = contentMapper.getMaxSerialNumByColumnId(params);
        if (maxSerialNum == null) {
            maxSerialNum = 1;
        } else {
            maxSerialNum += 1;
        }
        if (shopGoodsColumnDao.AddCloumnContent(columnId, contentIds, maxSerialNum)) {
            // 当内容从收费转为免费（被设置为免费浏览、关联免费专栏），若此内容参与返润，则将此商品转为“不参与”
            params.put("columnId", columnId);
            Map<String, Object> shopGoodsColumnDetail = shopGoodsColumnDao.getShopGoodsColumnDetail(params);
            Integer isFree = (Integer) shopGoodsColumnDetail.get("isFree");
            //需求改为不能选单独售卖的内容
            map.put("purchase", 2);
            for (Object item : contentIds) {
                // 小B内容是设置了返润，又被添加到大麦商城，此时把这个内容关联到免费的专栏，那么大麦商城要自动删除此内容。
                if (isFree == 1) {
                    Map<String, Object> contentId = new HashMap<>();
                    contentId.put("contentId", item);
                    ContentPo contentPo = contentMapper.contentInfo(contentId);
                    Long goodsId = contentPo.getGoodsId();
                    this.notJoining(goodsId.toString());
                }
                map.put("contentId", item);
                contentMapper.updatePurchase(map);//修改内容表销售方式(PURCHASE)
            }
            return true;
        } else {
            params.put("msg", "添加失败");
            return false;
        }
    }

    /*
     * 删除专栏、内容关联
     * columnId：专栏ID
     * contentId：要删除的内容ID
     * */
    public boolean DeleteCloumnContent(Map<String, Object> params) {
        Long columnId = params.get("columnId") != null ? Long.parseLong(params.get("columnId").toString()) : 0;
        Long contentId = params.get("contentId") != null ? Long.parseLong(params.get("contentId").toString()) : 0;
        Integer serialNum = contentMapper.getSerialNumByColumnIdAndContentId(params);
        if (shopGoodsColumnDao.DeleteCloumnContent(columnId, contentId)) {
            params.put("flag", 0);
            params.put("from", serialNum);
            contentMapper.updateSerialNumByColumnIdAndContentId(params);
            params.put("contentId", contentId);
            ContentPo contentPo = contentMapper.contentInfo(params);
            Integer purchase = null;
            if (contentPo.getPurchase() != null && contentPo.getPurchase() == 3) {
                purchase = 1;
            }
            params.put("purchase", purchase);
            params.put("isFree", 0);
            contentMapper.updatePurchase(params);//修改内容表销售方式(PURCHASE)
            return true;
        } else {
            return false;
        }
    }


    public List<Map<String, Object>> getAllList(Map<String, Object> params) {
        return shopGoodsColumnDao.getAllList(params);
    }
}